﻿using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using System.Text;
using Microsoft.Samples.ServiceHosting.StorageClient;

namespace BackupObjects.Taging
{
    /// <summary>
    /// CRUD access to tag.
    /// </summary>
    public class TagRepository : BaseTableRepository<Tag, TagRow>
    {
        private const string TagTableName = "Tag";

        public TagRepository(int numRetries)
            : base(numRetries)
        {
        }

        public TagRepository():base()
        {

        }

        public override string TableName
        {
            get { return TagTableName; }
        }

        /// <summary>
        /// Get all the childrens of the given tag.
        /// </summary>
        /// <param name="tag"></param>
        /// <returns></returns>
        public List<Tag> GetChildrens(Tag tag)
        {
            var parentId = tag.Id.ToString();
            var query = DataServiceQuery().Where(item => item.Parent == parentId);

            TableStorageDataServiceQuery<TagRow> dataServiceQuery =
                new TableStorageDataServiceQuery<TagRow>(query as DataServiceQuery<TagRow>, TableRetry);
            return dataServiceQuery
                .ExecuteWithRetries()
                .ToList()
                .ConvertAll<Tag>(item => item);
        }

        /// <summary>
        /// Get the parent of the given tag.
        /// </summary>
        /// <returns>The parent tag of the given tag</returns>
        public Tag GetParent(Tag tag)
        {
            if(!tag.Parent.HasValue)
            {
                return null;
            }

            return Load(tag.Parent.Value);
        }
    }
}
